//
//  Muscle.m
//  iBioCAD
//
//  Created by Orbitus on 10/23/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "Muscle.h"


@implementation Muscle

- (void) awakeFromNib
{
	[self init];
}

- (id)init {
    self = [super init];
	[[NSNotificationCenter defaultCenter] addObserver:self 
											selector:@selector(finishedMuscle:) 
												name:NSTaskDidTerminateNotification 
												object:nil];
	myMuscle = nil; // This is a good time to initialize the pointer
	return self;
}

- (IBAction)Muscle:(id)sender
{
	[muscleButton setTitle:@"Running..."];
	NSLog(@"Running ClustalW...");
    [muscleButton setEnabled:NO];
	
	[appRunningIndicator startAnimation:self];
	
	myMuscle = [[NSTask alloc] init];
	pipe = [[NSPipe alloc] init];
	NSFileHandle *handle;
	NSString *string;
	
	NSArray * dnaExportList = [dnaArrayController arrangedObjects];
	
	//NSLog(@"MOC= %@",[managedObjectContext description]);
	//NSLog(@"DNA EXport List= %@",[dnaExportList description]);
	
	//take that array and spit each name/sequence as a large fasta file
	//Output this file onto the friendly iBioCAD desktop
	

	
	myDesktopFolderPath	= @"/Sequences/iBioCAD/Desktop/sequence.fasta";
	musclePath = @"/UnixApps/muscle";
	
	[myMuscle setLaunchPath:musclePath];
	[myMuscle setCurrentDirectoryPath:myDesktopFolderPath];
	[myMuscle setArguments:[NSArray arrayWithObjects:@"-in", myDesktopFolderPath ,@"-out", @"/Sequences/iBioCAD/Desktop/muscle.fasta", nil]];
	[myMuscle setStandardOutput:pipe];
	
	//	handle=[NSFileHandle fileHandleForReadingAtPath:[myBinFolderPath stringByAppendingPathComponent: @"out.fasta"]];
	
	handle=[pipe fileHandleForReading];
	
	[myMuscle launch];
	
	//[NSThread detachNewThreadSelector:@selector(copyData:)
	//						toTarget:self withObject:handle];
	
	//string=[[NSString alloc] initWithData:[handle readDataToEndOfFile] encoding:NSASCIIStringEncoding]; // convert NSData -> NSString
    
    [muscleOutput setString:@"Finished Muscle Alignment"];
	NSLog(@"...Finished Muscle!");
	
}
- (void)copyData:(NSFileHandle*)handle {
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    NSData *data;
	
    while([data=[handle availableData] length]) { // until EOF (check reference)
        NSString *string=[[NSString alloc] initWithData:data
																										   encoding:NSASCIIStringEncoding];
        NSRange theEnd=NSMakeRange([[muscleOutput string] length],0);
		
        [muscleOutput replaceCharactersInRange:theEnd
																			   withString:string]; // append new string to the end
        theEnd.location+=[string length]; // the end has moved
        [muscleOutput scrollRangeToVisible:theEnd];
		
        [string release];
    }
	
    [pool release];
}

- (void)finishedMuscle:(NSNotification *)aNotification
{
	//[muscleButton setTitle:@"Muscle"];
	//[muscleButton setEnabled:YES];
	//[appRunningIndicator stopAnimation:self];
	
	//[myBlast release]; // Don't forget to clean up memory
    //[pipe release];
}

@end
